import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_country_Page.dart';
import 'package:flutter_application_cyber/model/cn_object_cache.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_application_cyber/tools/cn_log_pv_manger.dart';

class CnEditProfile extends StatefulWidget {
  const CnEditProfile({super.key});

  @override
  State<CnEditProfile> createState() => _EditProfileState();
}

class _EditProfileState extends State<CnEditProfile> {
  final myController = TextEditingController();
  final textFieldController = TextEditingController();
  String country = '';
  String nickname = '';
  String avatarUrl = '';
  String birthday = DateTime.now().toString().substring(0, 10);
  int notes = 0;
  File? imagePath;

  UserInfoModel getUserInfo() {
    return Provider.of<ChangeUserInfoModel>(context, listen: true).info;
  }

  @override
  void dispose() {
    myController.dispose();
    textFieldController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _initData();
  }

//获取用户信息
  void _initData() async {
    UserInfoModel userData = getUserInfo();
    setState(() {
      nickname = userData.nickname ?? '';
      avatarUrl = userData.avatarUrl ?? '';
      birthday = userData.birthday ?? '';
      country = userData.country ?? '';
    });
    myController.text = userData.nickname ?? '';
    textFieldController.text = userData.about ?? '';
  }

//选择出生日期
  _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: DateTime(int.parse(birthday.substring(0,4))),
        firstDate: DateTime(1930),
        lastDate: DateTime(2006));
    if (picked != null && picked.toString() != birthday) {
      setState(() {
        birthday = picked.toString().substring(0, 10);
      });
    }
  }

//上传大头像
  _postUploadImageToOssWithImage(File imagePath) {
    DateTime dateTime = DateTime.now();
    String fileName = imagePath.path.split('/').last;
    String format = fileName.split('.').last;
    int imageTimeName = dateTime.millisecondsSinceEpoch +
        (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';

    String dir = CnObjectCache.getInfo().ossPolicModel.dir;

    var params = {
      'ossaccessKeyId': CnObjectCache.getInfo().ossPolicModel.accessKeyId,
      'policy': CnObjectCache.getInfo().ossPolicModel.policy,
      'signature': CnObjectCache.getInfo().ossPolicModel.signature,
      'callback': CnObjectCache.getInfo().ossPolicModel.callback,
      'key': '$dir/$imageName',
    };
    EasyLoading.show(status: 'loading...');

    CnNetHelper.postUploadImageToOssWithImage(
        CnObjectCache.getInfo().ossPolicModel.host,
        params,
        imagePath.path,
        '$dir/$imageName', (HDHResponseData resp, bool result, String msg) {
      EasyLoading.dismiss();

      if (result) {
        print(resp.data);
        var param = {'avatarPath': resp.data['filename']};
        CnNetHelper.updateAvatar(param,
            (HDHResponseData resp, bool result, String msg) {
          if (result) {
            _updateUserInfo();
          }
        });
      }
    });
  }

//更新用户信息
  _updateUserInfo() {
    var params = {
      'nickname': myController.text,
      'birthday': birthday,
      'country': country,
      'language': 'en',
      'about': textFieldController.text,
    };
    EasyLoading.show(status: 'loading...');
    CnNetHelper.saveUserInfo(params,
        (HDHResponseData configData, bool result, String msg) {
      EasyLoading.dismiss();
      if (result) {
        Navigator.pop(context, result);
      }
    });
  }

  Future<bool> requestCameraPermission() async {
    //获取当前的权限
    var status = await Permission.photos.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.photos.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  void _showCameraDialog(context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          contentPadding:
              const EdgeInsets.only(top: 4, left: 24, right: 24, bottom: 0),
          title: const Text('Prompt'),
          content: Container(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const SizedBox(height: 16),
                const Text(
                  'System permission camera.write external storage access denied',
                  style: const TextStyle(fontSize: 18, color: Colors.black),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 20, left: 0, right: 0),
                  height: 1,
                  color: Colors.black12,
                ),
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Container(
                        child: InkWell(
                          onTap: () {
                            //复制
                            Navigator.of(context).pop();
                          },
                          child: Container(
                            height: 40,
                            alignment: Alignment.center,
                            child: const Text('Later',
                                style: TextStyle(
                                    color: Colors.black, fontSize: 18)),
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 0),
                        width: 1,
                        height: 46,
                        color: Colors.black12,
                      ),
                      Container(
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context).pop();
                            // 打开手机上该app权限的页面
                            openAppSettings();
                          },
                          child: Container(
                            height: 40,
                            alignment: Alignment.center,
                            child: const Text('Go Settings',
                                style: TextStyle(
                                    color: Colors.black, fontSize: 18)),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        leading: const BackButton(color: Colors.black),
        title: const Text(
          'Edit Profile',
          style: TextStyle(color: Colors.black, fontSize: 18),
        ),
      ),
      body: Container(
        child: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  width: 90,
                  height: 90,
                  margin: const EdgeInsets.only(top: 30),
                  child: InkWell(
                    child: Stack(
                      clipBehavior: Clip.none,
                      children: [
                        Container(
                          width: 88,
                          height: 88,
                          clipBehavior: Clip.hardEdge,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(44)),
                          child: (imagePath != null)
                              ? Image.file(
                                  imagePath!,
                                  fit: BoxFit.cover,
                                  width: 88,
                                  height: 88,
                                )
                              : (avatarUrl != ''
                                  ? Image.network(
                                      avatarUrl,
                                      fit: BoxFit.cover,
                                      width: 88,
                                      height: 88,
                                    )
                                  : Image.asset(
                                      'images/icon_logo.png',
                                      width: 88,
                                      height: 88,
                                    )),
                        ),
                        Positioned(
                          top: 60,
                          left: 60,
                          child: Container(
                            width: 26,
                            height: 26,
                            child: Image.asset('images/icon_photo_mine.png'),
                          ),
                        ),
                      ],
                    ),
                    onTap: () async {
                      CnLogPvManger.stat(
                          page: 'editavatar',
                          subPage: 'subPage',
                          terPage: 'terPage',
                          broadcasterId: 'broadcasterId');

                      bool isOpenPhotos = await requestCameraPermission();
                      if (isOpenPhotos) {
                        XFile? pickedImage = await ImagePicker().pickImage(
                            source: ImageSource.gallery,
                            imageQuality: 70,
                            maxHeight: 100,
                            maxWidth: 100);
                        if (pickedImage != null) {
                          final File file = File(pickedImage.path);
                          setState(() {
                            imagePath = file;
                          });
                        }
                      } else {
                        _showCameraDialog(context);
                      }
                    },
                  ),
                ),
                Container(
                    child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      margin: const EdgeInsets.only(left: 16),
                      child: const Text(
                        'Nick Name',
                        style:
                            TextStyle(fontSize: 16, color: Color(0x4D000000)),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(right: 16, top: 5),
                      width: 200,
                      height: 50,
                      child: SingleChildScrollView(
                        child: TextField(
                          maxLength: 30,
                          controller: myController,
                          textAlign: TextAlign.right,
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(
                              borderSide: BorderSide(
                                width: 0,
                                style: BorderStyle.none,
                              ),
                            ),
                            hintText: 'Input your username',
                          ),
                        ),
                      ),
                    )
                  ],
                )),
                InkWell(
                  onTap: () {
                    _selectDate(context);
                  },
                  child: Container(
                    height: 50,
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            margin: const EdgeInsets.only(left: 16),
                            child: const Text(
                              'Date of Birth',
                              style: TextStyle(
                                  fontSize: 16, color: Color(0x4D000000)),
                            ),
                          ),
                          Container(
                            margin: const EdgeInsets.only(right: 12),
                            child: Row(
                              children: [
                                Text(birthday,
                                    style: const TextStyle(fontSize: 18)),
                                Image.asset(
                                  'images/ic_arrow_black.png',
                                  width: 20,
                                  height: 15,
                                ),
                              ],
                            ),
                          ),
                        ]),
                  ),
                ),
                InkWell(
                  onTap: () async {
                    final result = await Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const CnCountryPage()),
                    );
                    if (result != null) {
                      setState(() {
                        country = result.split(' +')[0];
                      });
                    }
                  },
                  child: Container(
                    height: 50,
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            margin: const EdgeInsets.only(left: 16),
                            child: const Text(
                              'Country',
                              style: TextStyle(
                                  fontSize: 16, color: Color(0x4D000000)),
                            ),
                          ),
                          Container(
                            margin: const EdgeInsets.only(right: 12),
                            child: Row(
                              children: [
                                Text(country,
                                    style: const TextStyle(fontSize: 18)),
                                Image.asset(
                                  'images/ic_arrow_black.png',
                                  width: 20,
                                  height: 15,
                                ),
                              ],
                            ),
                          ),
                        ]),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.only(left: 16, top: 16),
                  child: Row(
                    children: [
                      Text('Introduction:',
                          style: TextStyle(
                            color: Color(0x4D000000),
                            fontSize: 16,
                          ))
                    ],
                  ),
                ),
                Container(
                    padding: const EdgeInsets.all(16),
                    child: Stack(
                      children: [
                        TextField(
                            controller: textFieldController,
                            onChanged: (value) {
                              if (value.length < 300) {
                                setState(() {
                                  notes = value.length;
                                });
                              } else {
                                EasyLoading.showError('Up to 300 words！');
                              }
                            },
                            maxLines: 4,
                            decoration: const InputDecoration(
                              hintText: "Type in here ...",
                              border: OutlineInputBorder(),
                            )),
                        Positioned(
                          right: 16,
                          bottom: 10,
                          child: Row(
                            children: [
                              Text('${notes}/300',
                                  style: const TextStyle(
                                    color: Color(0x4D000000),
                                    fontSize: 16,
                                  ))
                            ],
                          ),
                        ),
                      ],
                    )),
                Container(
                  padding: const EdgeInsets.only(top: 40),
                  child: InkWell(
                    onTap: () {
                      // if (!ClickUtils.isClick()) return;

                      if (imagePath != null) {
                        _postUploadImageToOssWithImage(imagePath!);
                      } else {
                        _updateUserInfo();
                      }
                    },
                    child: Container(
                        margin: const EdgeInsets.only(
                            left: 12, right: 12, bottom: 30),
                        alignment: Alignment.center,
                        height: 44,
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage(
                                    'images/icon_btn_bg_comment.png'))),
                        child: const Text(
                          'Submit',
                          style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: 19,
                          ),
                          textAlign: TextAlign.center,
                        )),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
